package com.lxr.test5002;

import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.cn.techvision.systemtoolservice.SystemTool;
import com.cn.techvision.systemtoolservice.SystemToolInfo;
import com.lxr.test5002.base.BaseActivity;
import com.lxr.test5002.base.Constants;
import com.lxr.test5002.utils.RefreshViewUtils;
import com.sdk.devicemanager.DEVICEcon;
import com.sdk.devicemanager.ICcon;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;

import butterknife.BindView;

/**
 * 类描述:[系统控制接口]
 * 说明: 请升级到最新版本
 *
 * @author: LXR-zsm
 * @Date: 2023/12/21 14:12
 */
public class SettingActivity extends BaseActivity implements View.OnTouchListener {
    private static final String TAG = SettingActivity.class.getSimpleName();
    @BindView(R.id.tv_pcie_status)
    TextView tvStatus;

    @BindView(R.id.btn_gesture)
    Button btnGesture;
    @BindView(R.id.btn_setting_pwd)
    Button btnPwd;
    @BindView(R.id.btn_insert)
    Button btnInsert;

    public SettingActivity() {
        super(R.layout.activity_setting);
    }

    private void updateStatus(String msg) {
        tvStatus.append(msg);
        tvStatus.append("\n");
//        int scrollAmount = tvStatus.getLayout().getLineTop(tvStatus.getLineCount())
//                - tvStatus.getHeight();
//        if (scrollAmount > 0)
//            tvStatus.scrollTo(0, scrollAmount + 30);
//        else
//            tvStatus.scrollTo(0, 0);
    }

    DEVICEcon devicEcon;
    SystemTool systemTool;
    SystemToolInfo systemToolInfo;
    int mMenuValue = 0, mGps = 0, mInsert = 0;
    String mNavigation = "system_nav_3buttons";
    boolean mGesture = false;
    boolean isShow = true;


    @Override
    protected void initView(Bundle savedInstanceState) {
        devicEcon = new DEVICEcon(this);
        systemTool = new SystemTool();
        systemToolInfo = new SystemToolInfo();
        tvStatus.setMovementMethod(ScrollingMovementMethod.getInstance());

    }

    @Override
    protected void initEvent() {
        findViewById(R.id.tv_menu).setOnClickListener(view -> {
            //控制状态栏
            //入口参数: status: 0状态栏关闭，1 状态栏打开
            //返回值:  Boolean  true:设置成功  false:设置失败
            boolean ret = devicEcon.set_menu(mMenuValue = mMenuValue == 0 ? 1 : 0);
            updateStatus("控制状态栏：" + (mMenuValue == 0 ? "关闭" : "打开") + (ret ? "成功" : "失败"));
        });

        findViewById(R.id.tv_navigation).setOnClickListener(view -> {
            //控制导航栏
            //入口参数: "system_nav_3buttons" 开启导航栏  "system_nav_gestural"  关闭导航栏
            //返回值:  int：0:打开成功  非0:打开失败
            boolean ret = devicEcon.setNavigationMode(mNavigation = (mNavigation.equals("system_nav_3buttons") ? "system_nav_gestural" : "system_nav_3buttons"));
            updateStatus("控制导航栏:" + mNavigation);
            if (mNavigation.equals("system_nav_3buttons")) {
                btnGesture.setEnabled(false);
            } else {
                btnGesture.setEnabled(true);
            }
            updateStatus("控制导航栏：" + (mNavigation.equals("system_nav_3buttons") ? "打开" : "关闭") + (ret ? "成功" : "失败"));
        });

        btnGesture.setOnClickListener(view -> {
            //5.3.4关闭导航栏，且屏蔽左右屏幕边缘滑动，触发返回功能
//           入口参数: status
//            true 屏蔽导航栏后，不屏蔽屏幕两边滑动，返回功能
//            false 屏蔽导航栏后，屏蔽屏幕两边滑动，返回功能
            //返回值: Boolean   true 设置成功  false 设置失败
            boolean ret = devicEcon.setGestureModeBackEnable(false);
            if (mGesture) {
                updateStatus("启用屏幕两边滑动：设置" + (ret ? "成功" : "失败"));
            } else {
                updateStatus("屏蔽屏幕两边滑动：设置" + (ret ? "成功" : "失败"));
            }
        });


        findViewById(R.id.tv_gps).setOnClickListener(view -> {
            //5.3.5开启和关闭GPS
            //入口参数: status  1 打开GPS    0 关闭GPS
            //返回值: Boolean   true 打开/关闭成功  false 打开/关闭失败
            boolean ret = devicEcon.set_location(mGps = mGps == 0 ? 1 : 0);
            updateStatus("GPS：" + (mGps == 0 ? "关闭" : "打开") + (ret ? "成功" : "失败"));
        });
        findViewById(R.id.tv_device_info).setOnClickListener(view -> {
            updateStatus("机器型号:" + Build.MODEL);
            updateStatus("生  产  商:" + Build.MANUFACTURER);
            updateStatus("固件版本:" + Build.DISPLAY);
            updateStatus("jar包版本:" + systemToolInfo.jarVs());
            updateStatus("基带版本号:" + getJD());
            updateStatus("SN:" + devicEcon.get_sys_parameter(1));
            updateStatus("起爆器编号:" + devicEcon.get_sys_parameter(2).replace("\n", ""));
            updateStatus("终端编号:" + devicEcon.get_sys_parameter(3).replace("\n", ""));
            updateStatus("IMEI:" + devicEcon.get_sys_parameter(4));
            updateStatus("WifiMac:" + devicEcon.get_sys_parameter(5));
            updateStatus("设备类型:" + devicEcon.get_sys_parameter(6));
            updateStatus("蓝牙MAC:" + devicEcon.get_sys_parameter(7));
        });
        findViewById(R.id.btn_switch).setOnClickListener(v -> {
            //安全开关状态
            // 返回值 ： int 10:关   11:开   -1：失败
            int ret = ICcon.getInstance().get_switchStatus();
            if (ret == -1)
                updateStatus("安全开关状态：获取失败" + ret);
            else {
                updateStatus("安全开关状态：" + (ret == 11 ? "打开" : "关闭") + "  返回值：" + ret);
            }
        });
        findViewById(R.id.btn_led).setOnClickListener(v -> new LEDThread().start());

        btnInsert.setOnClickListener(v -> {
            if (isShow) {
                updateStatus(getString(R.string.app_installation_setup));
                isShow = false;
            }
            //设置白名单方法，1：关闭，0：打开
            boolean ret = devicEcon.setAppInstallEnabled(mInsert);
            mInsert = mInsert == 0 ? 1 : 0;
            updateStatus("白名单：" + (mInsert == 0 ? "打开" : "关闭") + (ret ? "成功" : "失败"));

        });
        btnPwd.setOnClickListener(v -> {
            updateStatus(getString(R.string.app_setting_pwd));
        });
    }

    @Override
    protected void initData() {
        updateStatus("机器型号:" + Build.MODEL);
        updateStatus("生  产  商:" + Build.MANUFACTURER);
        updateStatus("固件版本:" + Build.DISPLAY);
        updateStatus("jar包版本:" + systemToolInfo.jarVs());
        updateStatus("基带版本号:" + getJD());
        updateStatus("SN:" + systemTool.flashId());
        updateStatus("蓝牙MAC:" + systemTool.getBtMac());
    }

    /**
     * 方法描述:[基带版本]
     *
     * @param
     * @author: LXR-zsm
     * @Date: 2023/12/19
     * @Return: java.lang.String
     */
    public String getJD() {
        String JD = null;
        try {
            Class e = Class.forName("android.os.SystemProperties");
            Method m = e.getMethod("get", new Class[]{String.class, String.class});
            Object result = m.invoke(null, new Object[]{"gsm.version.baseband", "no message"});
            JD = (String) result;
        } catch (Exception var6) {
            var6.printStackTrace();
        }
        return JD;
    }

    private float y1 = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            //按下去第一个Y坐标
            y1 = event.getY();
            //通知父控件不要干扰
            v.getParent().requestDisallowInterceptTouchEvent(true);
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (y1 - event.getY() > 50) {
                Log.e(TAG, "向上滑");
                v.getParent().requestDisallowInterceptTouchEvent(canVerticalScroll((TextView) v, true));
            } else if (event.getY() - y1 > 380) {
                Log.e(TAG, "向下滑: ");
                v.getParent().requestDisallowInterceptTouchEvent(canVerticalScroll((TextView) v, false));
            }

        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            v.getParent().requestDisallowInterceptTouchEvent(false);
        }
        return false;
    }

    /**
     * @param view 滑动的TextView
     * @param flag true 向上滑动 false 向下滑动
     * @return
     */
    protected boolean canVerticalScroll(TextView view, boolean flag) {
        //滚动的距离
        int scrollY = view.getScrollY();
        Log.e(TAG, "滚动距离: " + scrollY);
        //控件内容的总高度
        int scrollRange = view.getLayout().getHeight();
        Log.e(TAG, "控件内容的总高度: " + scrollRange);
        //控件实际显示的高度
        int scrollExtent = view.getHeight() - view.getCompoundPaddingTop() - view.getCompoundPaddingBottom();
        Log.e(TAG, "控件实际显示的高度: " + scrollExtent);
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;
        Log.e(TAG, "显示高度的差值: " + scrollDifference);
        if (flag) {
            return scrollDifference == scrollY ? false : true;
        } else {
            return scrollDifference == 0;
        }
    }

    private class LEDThread extends Thread {
        @Override
        public void run() {
            try {
                //需要系统权限
                writeToCtrlFile("/sys/class/leds/green/brightness", "255");
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "呼吸灯绿灯亮");
                Thread.sleep(1000);
                writeToCtrlFile("/sys/class/leds/green/brightness", "0");
                writeToCtrlFile("/sys/class/leds/red/brightness", "255");
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "呼吸灯红灯亮");
                Thread.sleep(1000);
                writeToCtrlFile("/sys/class/leds/red/brightness", "0");
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "呼吸灯关闭");
                Thread.sleep(1000);

                //0 灭  1 绿灯亮  2  红灯亮  3 红绿
                ICcon.getInstance().set_LEDStatus(1);
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "LED绿灯亮");
                Thread.sleep(1000);
                ICcon.getInstance().set_LEDStatus(2);
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "LED红灯亮");
                Thread.sleep(1000);
                ICcon.getInstance().set_LEDStatus(0);
                RefreshViewUtils.appendText(SettingActivity.this, tvStatus, "LED灯关闭");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void writeToCtrlFile(String path, String data) {
        try {
            FileOutputStream fps = new FileOutputStream(new File(path));
            fps.write(data.getBytes());
            fps.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.i(Constants.LOG_TAG, "onConfigurationChanged");
    }
}